<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 6.3.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" integrity="sha256-Z1K5uhUaJXA7Ll0XrZ/0JhX4lAtZFpT6jkKrEDT0drU=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"example.com","root":"/","images":"/images","scheme":"Muse","darkmode":false,"version":"8.14.1","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":{"enable":false,"style":null},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":-1,"unescape":false,"preload":false}}</script><script src="/js/config.js"></script>

    <meta name="description" content="前言使用消息代理的系统根据定义是分布式的。 由于发送的协议方法（消息）不能保证到达对等方或被其成功处理， 因此发布者和消费者都需要一种机制来进行传递和处理确认。RabbitMQ 支持的几种消息传递协议提供了这样的特性。  从代理（broker）对发布者（publisher）的确认是一个称为publisher-confirms（发布者确认）的扩展 协议。  从消费者（consumer）到 Rabbi">
<meta property="og:type" content="article">
<meta property="og:title" content="高可靠性的消息队列 —— RabbitMQ">
<meta property="og:url" content="http://example.com/2021/10/12/%E9%AB%98%E5%8F%AF%E9%9D%A0%E6%80%A7%E7%9A%84%E6%B6%88%E6%81%AF%E9%98%9F%E5%88%97%20%E2%80%94%E2%80%94%20RabbitMQ/index.html">
<meta property="og:site_name" content="JsyBlog">
<meta property="og:description" content="前言使用消息代理的系统根据定义是分布式的。 由于发送的协议方法（消息）不能保证到达对等方或被其成功处理， 因此发布者和消费者都需要一种机制来进行传递和处理确认。RabbitMQ 支持的几种消息传递协议提供了这样的特性。  从代理（broker）对发布者（publisher）的确认是一个称为publisher-confirms（发布者确认）的扩展 协议。  从消费者（consumer）到 Rabbi">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-10-11T16:00:00.000Z">
<meta property="article:modified_time" content="2021-10-12T15:03:57.247Z">
<meta property="article:author" content="SongyangJi">
<meta property="article:tag" content="Message Queue">
<meta property="article:tag" content="RabbitMQ">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="http://example.com/2021/10/12/%E9%AB%98%E5%8F%AF%E9%9D%A0%E6%80%A7%E7%9A%84%E6%B6%88%E6%81%AF%E9%98%9F%E5%88%97%20%E2%80%94%E2%80%94%20RabbitMQ/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"http://example.com/2021/10/12/%E9%AB%98%E5%8F%AF%E9%9D%A0%E6%80%A7%E7%9A%84%E6%B6%88%E6%81%AF%E9%98%9F%E5%88%97%20%E2%80%94%E2%80%94%20RabbitMQ/","path":"2021/10/12/高可靠性的消息队列 —— RabbitMQ/","title":"高可靠性的消息队列 —— RabbitMQ"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>高可靠性的消息队列 —— RabbitMQ | JsyBlog</title>
  








  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">JsyBlog</p>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%89%8D%E8%A8%80"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E7%94%9F%E4%BA%A7%E8%80%85%E5%8F%91%E5%B8%83%E6%B6%88%E6%81%AF%E4%B8%8D%E4%B8%A2%E5%A4%B1"><span class="nav-number">2.</span> <span class="nav-text">生产者发布消息不丢失</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BA%8B%E5%8A%A1%E6%9C%BA%E5%88%B6"><span class="nav-number">2.1.</span> <span class="nav-text">事务机制</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8F%91%E9%80%81%E6%96%B9%E7%A1%AE%E8%AE%A4%E6%9C%BA%E5%88%B6"><span class="nav-number">2.2.</span> <span class="nav-text">发送方确认机制</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#MQ%E6%9C%8D%E5%8A%A1%E5%99%A8%E5%AD%98%E5%82%A8%E6%B6%88%E6%81%AF%E4%B8%8D%E4%B8%A2%E5%A4%B1"><span class="nav-number">3.</span> <span class="nav-text">MQ服务器存储消息不丢失</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E6%B6%88%E8%B4%B9%E8%80%85%E6%B6%88%E8%B4%B9%E6%B6%88%E6%81%AF%E4%B8%8D%E4%B8%A2%E5%A4%B1"><span class="nav-number">4.</span> <span class="nav-text">消费者消费消息不丢失</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%85%B3%E4%BA%8EACK"><span class="nav-number">4.1.</span> <span class="nav-text">关于ACK</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#RabbitMQ%E7%9A%84Client"><span class="nav-number">4.1.1.</span> <span class="nav-text">RabbitMQ的Client</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Spring-AMQP"><span class="nav-number">4.1.2.</span> <span class="nav-text">Spring AMQP</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Ack%E7%9A%84%E7%9B%B8%E5%85%B3api"><span class="nav-number">4.2.</span> <span class="nav-text">Ack的相关api</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#deliveryTag%EF%BC%88%E4%BA%A4%E4%BB%98%E6%A0%87%E7%AD%BE%EF%BC%89"><span class="nav-number">4.2.1.</span> <span class="nav-text">deliveryTag（交付标签）</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%A1%AE%E8%AE%A4%EF%BC%88ack%EF%BC%89%E6%96%B9%E6%B3%95"><span class="nav-number">4.2.2.</span> <span class="nav-text">确认（ack）方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%8B%92%E7%BB%9D%EF%BC%88rejecj-nack%EF%BC%89%E6%96%B9%E6%B3%95"><span class="nav-number">4.2.3.</span> <span class="nav-text">拒绝（rejecj\nack）方法</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%B8%9A%E5%8A%A1%E4%B8%8A%E5%AE%9E%E7%8E%B0"><span class="nav-number">5.</span> <span class="nav-text">业务上实现</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%8A%95%E9%80%92%E5%A4%B1%E8%B4%A5%E7%9A%84%E6%B6%88%E6%81%AF%E5%A6%82%E4%BD%95%E5%A4%84%E7%90%86"><span class="nav-number">5.1.</span> <span class="nav-text">投递失败的消息如何处理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%B6%88%E8%B4%B9%E7%9A%84%E5%B9%82%E7%AD%89%E6%80%A7%E5%A6%82%E4%BD%95%E5%81%9A%E5%88%B0"><span class="nav-number">5.2.</span> <span class="nav-text">消费的幂等性如何做到</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%B6%88%E6%81%AF%E4%B8%AD%E9%97%B4%E4%BB%B6%E5%AE%9E%E7%8E%B0%E5%88%86%E5%B8%83%E5%BC%8F%E4%BA%8B%E5%8A%A1"><span class="nav-number">5.3.</span> <span class="nav-text">消息中间件实现分布式事务</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%8F%82%E8%80%83"><span class="nav-number">6.</span> <span class="nav-text">参考</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">SongyangJi</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">251</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">45</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">109</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>

        </div>
      </div>
    </div>

    
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2021/10/12/%E9%AB%98%E5%8F%AF%E9%9D%A0%E6%80%A7%E7%9A%84%E6%B6%88%E6%81%AF%E9%98%9F%E5%88%97%20%E2%80%94%E2%80%94%20RabbitMQ/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="SongyangJi">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="JsyBlog">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="高可靠性的消息队列 —— RabbitMQ | JsyBlog">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          高可靠性的消息队列 —— RabbitMQ
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>
      

      <time title="创建时间：2021-10-12 00:00:00 / 修改时间：23:03:57" itemprop="dateCreated datePublished" datetime="2021-10-12T00:00:00+08:00">2021-10-12</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E6%B6%88%E6%81%AF%E4%B8%AD%E9%97%B4%E4%BB%B6/" itemprop="url" rel="index"><span itemprop="name">消息中间件</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>使用消息代理的系统根据定义是分布式的。</p>
<p>由于发送的协议方法（消息）不能保证到达对等方或被其成功处理，</p>
<p>因此<strong>发布者和消费者都需要一种机制来进行传递和处理确认</strong>。RabbitMQ 支持的几种消息传递协议提供了这样的特性。</p>
<ul>
<li><p>从代理（broker）对发布者（publisher）的确认是一个称为<strong>publisher-confirms（发布者确认）</strong>的扩展 协议。</p>
</li>
<li><p>从消费者（consumer）到 RabbitMQ 的传递处理确认在消息传递协议中称为<strong>acknowledgement（简称 ack，计算机网络中经常用到）</strong>；</p>
</li>
</ul>
<p>这两个功能都基于相同的想法，并受到 TCP 的启发。</p>
<p>它们对于从发布者到 RabbitMQ 节点以及从 RabbitMQ 节点到消费者的可靠交付至关重要。换句话说，<strong>它们对于数据安全至关重要</strong>。</p>
<h1 id="生产者发布消息不丢失"><a href="#生产者发布消息不丢失" class="headerlink" title="生产者发布消息不丢失"></a>生产者发布消息不丢失</h1><blockquote>
<p>注意下面两种方案不可以同时选择，最多选其一。</p>
<p>即事务通道不能进入确认模式，并且确认模式的通道也不能成为事务通道。</p>
</blockquote>
<h2 id="事务机制"><a href="#事务机制" class="headerlink" title="事务机制"></a>事务机制</h2><ul>
<li>原生Java客户端</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">        <span class="type">Channel</span> <span class="variable">ch</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line"><span class="comment">// ...</span></span><br><span class="line">        ch.txSelect();</span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; MSG_COUNT; ++i) &#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                ch.basicPublish(<span class="string">&quot;&quot;</span>, QUEUE_NAME,</span><br><span class="line">                        MessageProperties.PERSISTENT_BASIC,</span><br><span class="line">                        <span class="string">&quot;nop&quot;</span>.getBytes());</span><br><span class="line">                ch.txCommit();</span><br><span class="line">            &#125; <span class="keyword">catch</span> (Exception exception) &#123;</span><br><span class="line">                ch.txRollback();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br></pre></td></tr></table></figure>



<ul>
<li>SpringBoot AMQP</li>
</ul>
<p>首先提供一个事务管理器供SpringBoot使用。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Bean</span></span><br><span class="line">RabbitTransactionManager <span class="title function_">transactionManager</span><span class="params">(ConnectionFactory connectionFactory)</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">RabbitTransactionManager</span>(connectionFactory);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>接下来，在消息生产者上面做两件事：添加<code>@Transactional</code>并设置通信信道为事务模式：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Service</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">MsgService</span> &#123;</span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    RabbitTemplate rabbitTemplate;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Transactional</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">send</span><span class="params">()</span> &#123;</span><br><span class="line">        rabbitTemplate.setChannelTransacted(<span class="literal">true</span>);</span><br><span class="line">     <span class="comment">// rabbitTemplate.convertAndSend(...);</span></span><br><span class="line">     <span class="comment">// int i = 1 / 0; 没有爆发异常，由spring提交事务，否则回滚（也就是不发生消息）</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>但是使用事务有两个问题。</p>
<p>首先channel长时间处于阻塞：发布者必须依次等待broker处理每条消息。</p>
<p>不过有时候发布者只要知道broker宕机时哪些消息尚未处理就足够了。</p>
<p>其次是事务实现的繁重性：每次提交都需要一个 fsync()，这需要很多时间才能完成。</p>
<blockquote>
<p>发布 10000 条消息需要 4 多分钟（具体参数机器性能决定，总之确实非常慢）</p>
</blockquote>
<h2 id="发送方确认机制"><a href="#发送方确认机制" class="headerlink" title="发送方确认机制"></a>发送方确认机制</h2><p>一旦通道进入确认模式，代理将在处理消息时确认消息。</p>
<p>由于这是<strong>异步完成</strong>的，生产者可以流式发布而不用等待代理，代理也可以有效地<strong>批量写入磁盘</strong>。</p>
<ul>
<li>原生Java客户端</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 消息追踪记录（如果需要线程安全并且有序，可以使用 ConcurrentSkipListMap ）</span></span><br><span class="line">   HashMap&lt;Long, String&gt; map = <span class="keyword">new</span> <span class="title class_">HashMap</span>&lt;&gt;();</span><br><span class="line">   <span class="comment">// 必须显式开启</span></span><br><span class="line">   channel.confirmSelect();</span><br><span class="line">   <span class="comment">// 监听被退回的消息(如消息路由到队列失败)</span></span><br><span class="line">   channel.addReturnListener(returnMessage -&gt; &#123;</span><br><span class="line">       System.out.println(<span class="string">&quot;return : &quot;</span> + System.currentTimeMillis());</span><br><span class="line">       <span class="keyword">try</span> &#123;</span><br><span class="line">           Thread.sleep(<span class="number">100</span>);</span><br><span class="line">       &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">           e.printStackTrace();</span><br><span class="line">       &#125;</span><br><span class="line">       <span class="keyword">try</span> &#123;</span><br><span class="line">           TimeUnit.SECONDS.sleep(<span class="number">10</span>);</span><br><span class="line">       &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">           e.printStackTrace();</span><br><span class="line">       &#125;</span><br><span class="line">       System.err.println(<span class="keyword">new</span> <span class="title class_">String</span>(returnMessage.getBody()) + <span class="string">&quot; publish fail!&quot;</span>);</span><br><span class="line">   &#125;);</span><br><span class="line"></span><br><span class="line">   <span class="comment">// 监听被到达或未到达交换机（exchange）的消息</span></span><br><span class="line">   channel.addConfirmListener(<span class="keyword">new</span> <span class="title class_">ConfirmListener</span>() &#123;</span><br><span class="line">       <span class="meta">@Override</span></span><br><span class="line">       <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">handleAck</span><span class="params">(<span class="type">long</span> deliveryTag, <span class="type">boolean</span> multiple)</span> <span class="keyword">throws</span> IOException &#123;</span><br><span class="line">           map.remove(deliveryTag); <span class="comment">// 发送成功，缓存清除掉</span></span><br><span class="line">       &#125;</span><br><span class="line"></span><br><span class="line">       <span class="meta">@Override</span></span><br><span class="line">       <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">handleNack</span><span class="params">(<span class="type">long</span> deliveryTag, <span class="type">boolean</span> multiple)</span> <span class="keyword">throws</span> IOException &#123;</span><br><span class="line">           System.err.println(map.get(deliveryTag) + <span class="string">&quot;not ack!&quot;</span>);</span><br><span class="line">           <span class="comment">// 下面可以进行重新发送等逻辑</span></span><br><span class="line">       &#125;</span><br><span class="line">   &#125;);</span><br><span class="line"></span><br><span class="line">   <span class="keyword">try</span> &#123;</span><br><span class="line">       <span class="type">Random</span> <span class="variable">random</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Random</span>();</span><br><span class="line">       <span class="type">int</span> <span class="variable">idx</span> <span class="operator">=</span> <span class="number">0</span>;</span><br><span class="line">       <span class="keyword">while</span> (idx &lt; <span class="number">1000</span>) &#123;</span><br><span class="line">           <span class="type">String</span> <span class="variable">message</span> <span class="operator">=</span> <span class="string">&quot;from server...&quot;</span> + (++idx);</span><br><span class="line">           <span class="comment">// 追踪记录</span></span><br><span class="line">           map.put(channel.getNextPublishSeqNo(), message);</span><br><span class="line">           <span class="comment">// 发送消息</span></span><br><span class="line">           channel.basicPublish(<span class="string">&quot;&quot;</span>, queue, MessageProperties.PERSISTENT_BASIC, message.getBytes(StandardCharsets.UTF_8));</span><br><span class="line"></span><br><span class="line">           TimeUnit.MILLISECONDS.sleep(random.nextInt(<span class="number">300</span>) + <span class="number">200</span>);</span><br><span class="line">       &#125;</span><br><span class="line">   &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">       System.out.println(<span class="string">&quot;以下为未成功发送的消息&quot;</span>);</span><br><span class="line">       <span class="comment">// 可以进行重试逻辑</span></span><br><span class="line">       map.values().forEach(s -&gt; System.out.println(<span class="string">&quot;not ack, may need publish again : &quot;</span> + s));</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>



<ul>
<li>SpringBoot AMQP</li>
</ul>
<p>首先<strong>在配置文件中配置中开启消息发送方确认机制</strong>。</p>
<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">spring:</span></span><br><span class="line">  <span class="attr">rabbitmq:</span></span><br><span class="line">    <span class="attr">publisher-returns:</span> <span class="literal">true</span></span><br><span class="line">    <span class="attr">publisher-confirm-type:</span> <span class="string">correlated</span></span><br></pre></td></tr></table></figure>



<p><code>publisher-confirm-type</code>有三种属性：</p>
<ol>
<li>none：表示禁用发布确认模式，默认即此。</li>
<li>correlated：使用相关消息确认，回调中触发。</li>
<li>simple：使用 <code>waitForConfirms()</code> 和 <code>waitForConfirmsOrDie()</code> 方法的进行确认。</li>
</ol>
<p>然后<strong>配置回调的监听器</strong>：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">PublisherConfirmConfig</span> <span class="keyword">implements</span> <span class="title class_">RabbitTemplate</span>.ConfirmCallback, RabbitTemplate.ReturnsCallback &#123;</span><br><span class="line"></span><br><span class="line">    RabbitTemplate rabbitTemplate;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">PublisherConfirmConfig</span><span class="params">(RabbitTemplate rabbitTemplate)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.rabbitTemplate = rabbitTemplate;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//@Bean 此处无需注入</span></span><br><span class="line">    RabbitTransactionManager <span class="title function_">transactionManager</span><span class="params">(ConnectionFactory connectionFactory)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">RabbitTransactionManager</span>(connectionFactory);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">confirm</span><span class="params">(CorrelationData correlationData, <span class="type">boolean</span> ack, String cause)</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;correlationData : &quot;</span>+correlationData);</span><br><span class="line">        <span class="keyword">if</span> (ack) &#123;</span><br><span class="line">            System.out.println(<span class="string">&quot;success&quot;</span>);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            System.err.println(<span class="string">&quot;cause : &quot;</span>+cause);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">returnedMessage</span><span class="params">(ReturnedMessage returned)</span> &#123;</span><br><span class="line">        System.err.println(returned);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="meta">@PostConstruct</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">initRabbitTemplate</span><span class="params">()</span> &#123;</span><br><span class="line">        rabbitTemplate.setConfirmCallback(<span class="built_in">this</span>);</span><br><span class="line">        rabbitTemplate.setReturnsCallback(<span class="built_in">this</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>发送消息：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 注意必须传入 CorrelationData，否则没有根据去跟踪（原生client使用deliveryTag跟踪）</span></span><br><span class="line">rabbitTemplate.convertAndSend(<span class="string">&quot;q1&quot;</span>, (Object) s, <span class="keyword">new</span> <span class="title class_">CorrelationData</span>(<span class="string">&quot;correlation id = &quot;</span> + count));</span><br></pre></td></tr></table></figure>





<h1 id="MQ服务器存储消息不丢失"><a href="#MQ服务器存储消息不丢失" class="headerlink" title="MQ服务器存储消息不丢失"></a>MQ服务器存储消息不丢失</h1><h1 id="消费者消费消息不丢失"><a href="#消费者消费消息不丢失" class="headerlink" title="消费者消费消息不丢失"></a>消费者消费消息不丢失</h1><h2 id="关于ACK"><a href="#关于ACK" class="headerlink" title="关于ACK"></a>关于ACK</h2><h3 id="RabbitMQ的Client"><a href="#RabbitMQ的Client" class="headerlink" title="RabbitMQ的Client"></a>RabbitMQ的Client</h3><p>RabbitMQ中<code>channel</code>在消费消息（<code>basicConsume(String queue, boolean autoAck, Consumer callback)</code>）的时候，指定的ack的含义如下：</p>
<ul>
<li>autoAck &#x3D; true</li>
</ul>
<p>当broker在消息发送后（写入TCP套接字后）此条消息就立即ack了，此条消息RabbitMQ服务器也不再保存了，</p>
<p>而丝毫不管收到消息的客户端是否处理。如果消费者在收到大量消息但没有处理的时候突然宕机了，那么那些未处理消息也就随着本地缓冲区的消失而消失了（服务器上也没有了）。</p>
<p>这种ack方式谨慎使用。</p>
<ul>
<li>autoAck &#x3D; false</li>
</ul>
<p>这种ack方式必须要求用户自己主动ack消息（<code>channel.basicAck</code>）,常常和prefetchCount配合使用（后面会介绍到）。</p>
<h3 id="Spring-AMQP"><a href="#Spring-AMQP" class="headerlink" title="Spring AMQP"></a>Spring AMQP</h3><p>需要注意的是Spring AMQP中配置的ack的含义和上面的ack含义是不一样的。</p>
<ul>
<li>auto（default）</li>
</ul>
<p>容器将根据侦听器是正常返回还是抛出异常来发出 ack&#x2F;nack。</p>
<ul>
<li>none</li>
</ul>
<p>这里的none和rabbitmq的auto是一个含义。</p>
<ul>
<li>manual</li>
</ul>
<p>用户必须通过channel去ack&#x2F;nack</p>
<p><strong>配置方式</strong></p>
<ul>
<li><p>yaml配置</p>
<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">spring:</span></span><br><span class="line">  <span class="attr">rabbitmq:</span></span><br><span class="line">    <span class="attr">listener:</span></span><br><span class="line">      <span class="attr">simple:</span></span><br><span class="line">        <span class="attr">acknowledge-mode:</span> <span class="string">auto</span></span><br></pre></td></tr></table></figure>

</li>
<li><p>方法级别（覆盖外部配置）</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RabbitListener(queues = &quot;ququeName&quot;, ackMode = &quot;manual&quot;)</span></span><br></pre></td></tr></table></figure></li>
</ul>
<h2 id="Ack的相关api"><a href="#Ack的相关api" class="headerlink" title="Ack的相关api"></a>Ack的相关api</h2><h3 id="deliveryTag（交付标签）"><a href="#deliveryTag（交付标签）" class="headerlink" title="deliveryTag（交付标签）"></a>deliveryTag（交付标签）</h3><p>当消费者（订阅）被注册时，消息将被 RabbitMQ 使用basic.deliver 方法传递。</p>
<p>该方法带有一个<em>交付标签</em>，它<strong>唯一地标识了一个通道上的交付</strong>。因此，<strong>交付标签的范围是每个channel</strong>。</p>
<p>交付标签是单调增长的正整数。确认交付的客户端库方法将交付标签作为参数。</p>
<p>由于交付标签的范围是每个通道，<strong>交付必须在接收它们的同一通道上得到确认</strong>。</p>
<p>在不同的通道上确认将导致“未知传递标签”协议异常并关闭通道。</p>
<h3 id="确认（ack）方法"><a href="#确认（ack）方法" class="headerlink" title="确认（ack）方法"></a>确认（ack）方法</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">oid <span class="title function_">basicAck</span><span class="params">(<span class="type">long</span> deliveryTag, <span class="type">boolean</span> multiple)</span></span><br></pre></td></tr></table></figure>
<p>multiple为true的时候，会将之前的消息都ack（即交付标签小于deliveryTag的消息都会被ack）</p>
<h3 id="拒绝（rejecj-nack）方法"><a href="#拒绝（rejecj-nack）方法" class="headerlink" title="拒绝（rejecj\nack）方法"></a>拒绝（rejecj\nack）方法</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">void</span> <span class="title function_">basicReject</span><span class="params">(<span class="type">long</span> deliveryTag, <span class="type">boolean</span> requeue)</span> </span><br></pre></td></tr></table></figure>
<p>requeue为true的时候会将消息重新入队，但必须要注意的是<strong>如果这个queue没有其他消费者，而本机由于某些原因会反复拉取这条消息并拒绝再拉取导致死循环。</strong>所以，在需要将消息重新入队的时候，需要注意消息重新入队的次数。</p>
<p>还有一个相似的方法，</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">basicNack(<span class="type">long</span> deliveryTag, <span class="type">boolean</span> multiple, <span class="type">boolean</span> requeue)</span><br></pre></td></tr></table></figure>

<p>多了个 multiple 参数，含义和上面ack的multiple的一致。</p>
<h1 id="业务上实现"><a href="#业务上实现" class="headerlink" title="业务上实现"></a>业务上实现</h1><h2 id="投递失败的消息如何处理"><a href="#投递失败的消息如何处理" class="headerlink" title="投递失败的消息如何处理"></a>投递失败的消息如何处理</h2><h2 id="消费的幂等性如何做到"><a href="#消费的幂等性如何做到" class="headerlink" title="消费的幂等性如何做到"></a>消费的幂等性如何做到</h2><h2 id="消息中间件实现分布式事务"><a href="#消息中间件实现分布式事务" class="headerlink" title="消息中间件实现分布式事务"></a>消息中间件实现分布式事务</h2><h1 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h1><p><a target="_blank" rel="noopener" href="https://blog.rabbitmq.com/posts/2011/02/introducing-publisher-confirms">介绍发布者确认</a></p>
<p><a target="_blank" rel="noopener" href="https://rabbitmq.com/tutorials/tutorial-seven-java.html">发布者确认</a> </p>
<p><a target="_blank" rel="noopener" href="https://rabbitmq.com/confirms.html#consumer-acks-api-elements">消费者确认和发布者确认</a></p>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/Message-Queue/" rel="tag"># Message Queue</a>
              <a href="/tags/RabbitMQ/" rel="tag"># RabbitMQ</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2021/10/10/%E8%BF%90%E8%A1%8C%E3%80%81%E7%AE%A1%E7%90%86%E3%80%81%E9%85%8D%E7%BD%AERabbitMQ/" rel="prev" title="运行、管理、配置RabbitMQ">
                  <i class="fa fa-chevron-left"></i> 运行、管理、配置RabbitMQ
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2021/10/15/Spring%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%901/" rel="next" title="Spring源码解析1">
                  Spring源码解析1 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">SongyangJi</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/muse/" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>
  <div class="sidebar-dimmer"></div>
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/hexo-generator-searchdb/1.4.1/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>





  





</body>
</html>
